﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;


namespace FSC.HaNamAPApplication
{
    public partial class HNAP_AdminAPEdit : System.Web.UI.UserControl
    {
        private string modeform
        {
            get{
                string modeform = "a";
                if (Request.QueryString["m"] != null && Request.QueryString["m"].ToString() != "")
                {
                    modeform = Request.QueryString["m"].ToString();
                }
                return modeform;
            }
        }

        private int apid
        {
            get
            {
                int apid = -1;
                if (Request.QueryString["aid"] != null && int.TryParse(Request.QueryString["aid"].ToString(),out apid))
                {
                    apid = int.Parse(Request.QueryString["aid"].ToString());
                }
                return apid;
            }
        }
        
        public string CurrentUrlWithoutParam
        {
            get
            {
                return Controler.UrlWithoutParam(Request.RawUrl);
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDrop();
                BindDropDocsDialog();

                if (this.modeform.Equals("u"))
                {
                    LoadData();
                }
            }
        }

        /// <summary>
        /// Update attach files into 'Documents' document libraries of sharepoint.
        /// </summary>
        private void UploadFiles(int iAPId)
        { 
            SPSite objSite;
            SPWeb objWeb;
            HttpFileCollection uploadedFiles = HttpContext.Current.Request.Files;

            if (uploadedFiles.Count > 0)
            {
                objSite = SPControl.GetContextSite(Context);
                objWeb = objSite.OpenWeb();
                objWeb.AllowUnsafeUpdates = true;
                SPList objList = objWeb.Lists["Documents"];
                objList.AnonymousPermMask64 = SPBasePermissions.ViewListItems | SPBasePermissions.OpenItems
                                                | SPBasePermissions.Open | SPBasePermissions.ViewFormPages
                                                | SPBasePermissions.AddListItems;

                SPDocumentLibrary objLib = null;
                objLib = (SPDocumentLibrary)objList;
                objLib.AnonymousPermMask64 = SPBasePermissions.ViewListItems | SPBasePermissions.OpenItems
                                                | SPBasePermissions.Open | SPBasePermissions.ViewFormPages
                                                | SPBasePermissions.AddListItems;

                SPFolder rFolder = objLib.RootFolder;

                HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
                List<AdminProceduresFile> APFileList = new List<AdminProceduresFile>();
                bool IsInsert = false;

                for (int i = 0; i < uploadedFiles.Count; i++)
                {
                    SPFile objFile = null;
                    byte[] byteArr = null;
                    HttpPostedFile userPostedFile = uploadedFiles[i];

                    if (userPostedFile.ContentLength == 0)
                    {
                        continue;
                    }
                    IsInsert = true;

                    Stream fStream = userPostedFile.InputStream;
                    byteArr = new byte[fStream.Length];
                    fStream.Read(byteArr, 0, (int)fStream.Length);
                    fStream.Close();

                    objFile = rFolder.Files.Add(rFolder.Url + "/" + userPostedFile.FileName + "", byteArr, true);
                    objFile.Update();

                    AdminProceduresFile objAPF = new AdminProceduresFile();
                    objAPF.AP_ID = iAPId;
                    objAPF.Name = (Request.Form["fText" + i].ToString().Trim() != "") ? Request.Form["fText" + i].ToString() : userPostedFile.FileName;
                    objAPF.Path = GetUrlWithoutDomain(rFolder.ParentWeb.Url + "/" + rFolder.Url) + "/" + userPostedFile.FileName;

                    APFileList.Add(objAPF);

                    //Test
                    //Response.Write(GetUrlWithoutDomain(rFolder.ParentWeb.Url + "/" + rFolder.Url) + "/" + userPostedFile.FileName);
                }

                if (IsInsert)
                {
                    db.AdminProceduresFiles.InsertAllOnSubmit(APFileList);
                    db.SubmitChanges();
                }
            }
        }

        /// <summary>
        /// Deleting item from document libraries in Sharepoint
        /// </summary>
        /// <param name="web">This is the start web for the search for documents. Only sites that are at this level or below will be searched.</param>
        /// <param name="docName">This is the name of the document library to look for in each site. In our case it is always “Background Information Library</param>
        /// <param name="fileName">This is file name to delete.</param>
        private void DelFileInDocLib(SPWeb web, string docName,string fileName)
        {
            foreach (SPList list in web.Lists)
            {
                if (list.BaseType == SPBaseType.DocumentLibrary)
                {
                    SPDocumentLibrary lib = list as SPDocumentLibrary;
                    if (lib.Title == docName)
                    {
                        List<string> filesToDelete = new List<string>();
                        foreach (SPListItem item in lib.Items) 
                        {
                            SPFile file = null;

                            if (item.Name == fileName)
                            {
                                file = item.File;
                                if (file != null)
                                {
                                    filesToDelete.Add(file.Url);
                                    //Response.Write(String.Format("In DocLib: {0} ({2}) File - {1} ({3})", web.Title, item.Name, web.Url, file.Length));
                                }
                                break;
                            }
                        }

                        // Delete item
                        SPFolder folder = lib.ParentWeb.GetFolder(docName);
                        foreach (string url in filesToDelete)
                        {
                            folder.Files.Delete(url);
                            //Console.WriteLine("Deleted:" + url);
                        }
                        folder.Update();
                        lib.Update();
                    }
                }
            }
            //De quy de tim o cap thap hon
            //FindDocumentLibraries(web.Webs, name, operation);
        }

        private void BindDrop()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            
            // Bind Fields
            var dataField = from f in db.Fields
                            orderby f.Name
                            select f;
            ddlField.DataValueField = "Field_ID";
            ddlField.DataTextField = "Name";
            ddlField.DataSource = dataField;
            ddlField.DataBind();

            ddlField.Items.Insert(0, new ListItem("--Chọn lĩnh vực--", "-1"));

            // Bind Offices
            var dataOffice = from o in db.Offices
                             orderby o.Name
                             select new
                             {
                                 o.Office_ID,
                                 o.Name
                             };
            ddlOffice.DataValueField = "Office_ID";
            ddlOffice.DataTextField = "Name";
            ddlOffice.DataSource = dataOffice;
            ddlOffice.DataBind();

            ddlOffice.Items.Insert(0, new ListItem("--Chọn cơ quan--", "-1"));
        }

        private void BindDropDocsDialog()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);

            // Bind Fields
            var dataField = from f in db.Fields
                            orderby f.Name
                            select f;
            ddlDocFields.DataValueField = "Field_ID";
            ddlDocFields.DataTextField = "Name";
            ddlDocFields.DataSource = dataField;
            ddlDocFields.DataBind();

            ddlDocFields.Items.Insert(0, new ListItem("--Không lĩnh vực--", "-1"));

            // Bind Offices
            var dataOffice = from o in db.Offices
                             orderby o.Name
                             select new
                             {
                                 o.Office_ID,
                                 o.Name
                             };
            ddlDocOffices.DataValueField = "Office_ID";
            ddlDocOffices.DataTextField = "Name";
            ddlDocOffices.DataSource = dataOffice;
            ddlDocOffices.DataBind();

            ddlDocOffices.Items.Insert(0, new ListItem("--Không cơ quan--", "-1"));
        }

        private void LoadData()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            AdminProcedure objAP = db.AdminProcedures.SingleOrDefault(a => a.AP_ID == this.apid);
            if (objAP != null)
            {
                txtName.Text = objAP.Name;
                ddlField.SelectedValue = objAP.Field_ID.ToString();
                ddlOffice.SelectedValue = objAP.ExecuteOffice_ID.ToString();

                txtSteps.Text = Server.HtmlDecode(objAP.Steps);
                txtCompositionOfRecord.Text = Server.HtmlDecode(objAP.CompositionOfRecord);
                txtNumberOfRecord.Text = objAP.NumberOfRecords;
                txtTimeLimitPerform.Text = objAP.TimeLimitPerform;
                txtSubjectPerform.Text = objAP.SubjectsPerform;
                txtResultPerformAP.Text = objAP.ResultPerformAP;
                txtFee.Text = objAP.Fee;
                txtRequestAP.Text = Server.HtmlDecode(objAP.RequestAP);
                txtHowToPerform.Text = objAP.HowToPerform;

                cbEffectStatus.Checked = objAP.EffectStatus;
                cbCommentStatus.Checked = objAP.CommentStatus;

                BindRepeaterAttachFile();
                BindRepeaterLegal();
            }
        }

        private void BindRepeaterLegal()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            var APDocData = from a in db.AP_Documents
                            where a.AP_ID == this.apid
                            select new
                            {
                                Name = a.Document.Name,
                                ID = a.Doc_ID
                            };
            rptLegal.DataSource = APDocData;
            rptLegal.DataBind();

            string docIdValue = "";
            foreach (var item in APDocData)
            {
                docIdValue += item.ID + "#";
            }
            if (docIdValue != "")
            {
                // Cat bo # cuoi cung
                docIdValue = docIdValue.Substring(0, docIdValue.Length - 1);
            }
            hdfDocsExist.Value = docIdValue;
        }

        private void UpdateData()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            AdminProcedure objAP;

            if (this.modeform.Equals("u"))
                objAP = db.AdminProcedures.SingleOrDefault(a => a.AP_ID == this.apid);
            else
                objAP = new AdminProcedure();

            if (objAP == null) return;

            objAP.Name = txtName.Text;
            objAP.Field_ID = int.Parse(ddlField.SelectedValue);
            objAP.ExecuteOffice_ID = int.Parse(ddlOffice.SelectedValue);
            objAP.EffectStatus = cbEffectStatus.Checked;
            objAP.CommentStatus = cbCommentStatus.Checked;
            objAP.Steps = txtSteps.Text;
            objAP.CompositionOfRecord = txtCompositionOfRecord.Text;
            objAP.NumberOfRecords = txtNumberOfRecord.Text;
            objAP.TimeLimitPerform = txtTimeLimitPerform.Text;
            objAP.SubjectsPerform = txtSubjectPerform.Text;
            objAP.ResultPerformAP = txtResultPerformAP.Text;
            objAP.Fee = txtFee.Text;
            objAP.RequestAP = txtRequestAP.Text;
            //objAP.LegalGrounds = txtLegalGrounds.Text;
            objAP.HowToPerform = txtHowToPerform.Text;

            if (this.modeform.Equals("a"))
            {
                db.AdminProcedures.InsertOnSubmit(objAP);
            }

            db.SubmitChanges();

            //Update attach file
            UploadFiles(objAP.AP_ID);

            //Update Legal Grounds
            UpdateLegalGrounds(objAP.AP_ID);

            Response.Redirect(CurrentUrlWithoutParam + "?page=AdminAP");
        }

        private void UpdateLegalGrounds(int paramAPId)
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            List<AP_Document> APDocList = new List<AP_Document>();

            for (int i = 0; i < Request.Form.Count; i++)
            {
                if (Request.Form[i].ToString().Contains("doc#"))
                {
                    AP_Document obj = new AP_Document();
                    obj.Doc_ID = int.Parse(Request.Form[i].ToString().Substring(4));
                    obj.AP_ID = paramAPId;

                    APDocList.Add(obj);
                }
            }

            if (APDocList.Count > 0)
            {
                db.AP_Documents.InsertAllOnSubmit(APDocList);
                db.SubmitChanges();
            }
        }

        private void BindRepeaterAttachFile()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            var data = from a in db.AdminProceduresFiles
                       where a.AP_ID == apid
                       select new 
                       {
                           Link = a.Path,
                           Name = a.Name,
                           ID = a.ADFile_ID
                       };
            rptAttachFile.DataSource = data;
            rptAttachFile.DataBind();
        }

        private string GetNameWithExtension(string fullPath)
        {
            if (fullPath.LastIndexOf("/") != -1)
            {
                return fullPath.Substring(fullPath.LastIndexOf("/") + 1, fullPath.Length - fullPath.LastIndexOf("/") -1);
            }
            else
            {
                return fullPath;
            }
        }

        private string GetUrlWithoutDomain(string strUrl)
        {
            if (strUrl.IndexOf("http://") == -1) return strUrl;
            
            strUrl = strUrl.Substring(7);
            return strUrl.Substring(strUrl.IndexOf("/"));
        }

        protected void lbtUpdate_Click(object sender, EventArgs e)
        {
            UpdateData();
        }

        protected void rptAttachFile_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("del"))
            {
                HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
                AdminProceduresFile obj = db.AdminProceduresFiles.SingleOrDefault(a => a.ADFile_ID == int.Parse(e.CommandArgument.ToString()));
                if (obj != null)
                {
                    //Delete file in doc libraries in sharepoint
                    SPSite objSite = SPControl.GetContextSite(Context);
                    SPWeb objWeb = objSite.OpenWeb();
                    DelFileInDocLib(objWeb, "Documents", GetNameWithExtension(obj.Path));
                    
                    //Delete in database
                    db.AdminProceduresFiles.DeleteOnSubmit(obj);
                    db.SubmitChanges();

                    BindRepeaterAttachFile();
                }
            }
        }

        protected void rptLegal_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("del"))
            {
                HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
                AP_Document obj = db.AP_Documents.SingleOrDefault(a => a.AP_ID == this.apid && a.Doc_ID == int.Parse(e.CommandArgument.ToString()));
                if (obj != null)
                {
                    db.AP_Documents.DeleteOnSubmit(obj);
                    db.SubmitChanges();

                    BindRepeaterLegal();
                }
            }
        }
    }
}